package com.hmy.pig.service.impl;

import com.alibaba.excel.EasyExcel;
import com.hmy.pig.domain.HmyPig;
import com.hmy.pig.mapper.PigMapper;
import com.hmy.pig.service.QrCodeService;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 *  * @param null
 * @return
 * @author kdq
 * @date 2024/2/20 17:01
 * @description 批量插入猪只档案
 */

@Service
public class HmyPigServiceImpl {

    @Resource
    private PigMapper hmyPigMapper;
    @Autowired
    private QrCodeService qrCodeService;
    int i = 0;
    private static final Logger log = LoggerFactory.getLogger(HmyPigServiceImpl.class);
    ExecutorService executorService = Executors.newFixedThreadPool(4);


    /**
     * 导出数据到 Excel
     *
     * @param
     */
    public void export() throws IOException {

        List<HmyPig> pigList = hmyPigMapper.selectPigList(null,null,null,null);

        int totalpage = (int) Math.ceil((double) pigList.size() / 10000);

        for(int i = 0;i<totalpage;i++){
            int finalI = i;
            int startIndex = i * 10000;
            int endIndex = Math.min(startIndex + 10000, pigList.size());
            List<HmyPig> pigList1 = pigList.subList(startIndex, endIndex);
            // 将数据写入Excel
            executorService.submit(()->{
                EasyExcel.write("D:\\Downloads\\猪只档案"+ finalI +".xlsx", HmyPig.class)
                        // 在 write 方法之后， 在 sheet方法之前都是设置WriteWorkbook的参数
                        .sheet("猪只档案表" + finalI)
                        .doWrite(() -> {
                            // 分页查询数据
                            return pigList1;
                        });
            });
        }
    }







//    @Transactional(rollbackFor = Throwable.class)
    public void batchInsert(List<HmyPig> dataList){
        if (dataList != null && !dataList.isEmpty()) {
                for (HmyPig pig : dataList) {
                qrCodeService.upload(pig);
            }
            // 执行代码
        }
        executorService.submit(()->{
            hmyPigMapper.batchInsert(dataList);
        });
    }



}
